# Direct outputs eligible for public release

# GLOBAL SETTINGS --------------------------------------------------------------

options(
    scipen = 999,
    digits = 16,
    max.print = .Machine$integer.max,
    show.error.locations = TRUE,
    warn = 1
)

RNGkind("L'Ecuyer-CMRG")
seed <- 818675309L
set.seed(seed) # setting main seed

# PACKAGES ---------------------------------------------------------------------
library(data.table)
library(ggplot2)
library(scales)
library(viridisLite)

# PACKAGE SETTINGS -------------------------------------------------------------

# data.table
setDTthreads(threads = 1L)
options(datatable.print.class = TRUE, datatable.print.keys = TRUE)
# so that printing the data.table also shows the variable type on top

# BEGIN FILE -------------------------------------------------------------------

# Just in case something masks 'source()', use extra deliberate base::source().
base::source("~/code/0-utility-functions/table-and-text-utils.R", local = TRUE)

# READ IN OUR DATA -------------------------------------------------------------

moved_tract_nbhd_qual_dt <-
    readRDS(
        "~/estimation-output/event_study_estimates_moved_tract_neighborhood_quality.rds" # nolint
    )

# Map coefficients into shares (since they decompose the total moving effect)
moved_tract_nbhd_qual_dt[
    ,
    share := (estimate / sum(estimate)),
    by = .(attribute_label)
]

# Reordering labels and cleaning up
moved_tract_nbhd_qual_dt[
    ,
    valence := factor(valence, levels = c("Downward", "Upward"))
]
setorderv(
    moved_tract_nbhd_qual_dt,
    c("attribute_label", "valence"),
    order = c(1L, -1L)
)
moved_tract_nbhd_qual_dt[
    ,
    segment_label := cumsum(share) - (0.5 * share),
    by = .(attribute_label)
]

# Reordering labels and cleaning up
moved_tract_nbhd_qual_dt[, header_group := as.character(NA)]
moved_tract_nbhd_qual_dt[
    attribute_label == "Opportunity Atlas",
    header_group := "OA"
]
moved_tract_nbhd_qual_dt[
    attribute_label == "Childhood Opportunity Index",
    header_group := "COI"
]
moved_tract_nbhd_qual_dt[
    attribute_label == "Area Deprivation Index",
    header_group := "ADI"
]
moved_tract_nbhd_qual_dt[is.na(header_group), header_group := "Quality Proxies"]

moved_tract_nbhd_qual_dt[
    attribute_label == "Opportunity Atlas",
    attribute_label := "Opportunity  \nAtlas  "
]
moved_tract_nbhd_qual_dt[
    attribute_label == "Childhood Opportunity Index",
    attribute_label := "Childhood   \nOpportunity   \nIndex   "
]
moved_tract_nbhd_qual_dt[
    attribute_label == "Area Deprivation Index",
    attribute_label := "Area   \nDeprivation   \nIndex   "
]

moved_tract_nbhd_qual_dt[
    attribute_label == "College+ Attainment",
    attribute_label := "College+\nAttainment"
]
moved_tract_nbhd_qual_dt[
    attribute_label == "Median Rent (2BR)",
    attribute_label := "Median Rent\n(2BR)"
]

moved_tract_nbhd_qual_dt[
    ,
    header_group :=
        factor(
            header_group,
            levels = c(
                "OA",
                "COI",
                "ADI",
                "Quality Proxies"
            )
        )
]

moved_tract_nbhd_qual_dt[
    ,
    attribute_label :=
        factor(
            attribute_label,
            levels =
                rev(
                    c(
                        "Opportunity  \nAtlas  ",
                        "Childhood   \nOpportunity   \nIndex   ",
                        "Area   \nDeprivation   \nIndex   ",
                        "Poverty",
                        "College+\nAttainment",
                        "Test Scores",
                        "Teen Birth",
                        "Single Parents",
                        "Median Rent\n(2BR)"
                    )
                )
        )
]

bar_fill <- rev(viridis(n = 2))
bar_colors <- rev(bar_fill)
overall_mean_upward <-
    fmt_fixed_decimal(
        input = mean(moved_tract_nbhd_qual_dt[valence == "Upward"]$share),
        sub_for_missing = "-",
        should_be_rounded = TRUE,
        round_digits = 2L,
        decimal_digits = 2L,
        scale_factor = NA,
        add_comma = FALSE
    )

figure_5_5_a <-
    ggplot(
        data = moved_tract_nbhd_qual_dt,
        aes(x = attribute_label, y = share, fill = valence)
    ) +
    geom_bar(stat = "identity") +
    theme_bw(base_size = 10) +
    scale_y_continuous(
        breaks = (seq.int(from = 0, to = 100, by = 10) / 100),
        sec.axis = sec_axis(~.,
            breaks = as.numeric(overall_mean_upward),
            labels = overall_mean_upward
        ),
        expand = expansion(mult = c(0.005, 0.005))
    ) +
    labs(x = NULL, y = "Decomposition of Move by Destination Characteristics") +
    coord_flip(ylim = c(0, 1)) +
    facet_grid(
        header_group ~ .,
        space = "free",
        scales = "free",
        switch = "y"
    ) +
    theme(
        panel.grid.minor = element_blank(), # remove actual gridlines
        panel.grid.major = element_blank(),
        legend.position = "bottom",
        legend.title = element_blank(),
        legend.key.size = unit(1.75, "lines"),
        strip.placement = "outside",
        panel.spacing.y = unit(0, "cm"),
        strip.text.y = element_text(angle = 270, size = 8),
        panel.border = element_blank(),
        axis.line = element_line(),
        axis.text.y = element_text(hjust = 0.5)
    ) +
    scale_fill_manual(values = bar_fill) +
    scale_color_manual(values = bar_colors) +
    guides(fill = guide_legend(, reverse = TRUE)) +
    geom_hline(
        yintercept = as.numeric(overall_mean_upward),
        color = "#999999",
        linewidth = 1.5
    )

ggsave(
    plot = figure_5_5_a,
    filename = "~/paper/figures/figure-5.5a.png",
    width = 6,
    height = 4.5,
    dpi = 600
)

ggsave(
    plot = figure_5_5_a,
    filename = "~/paper/figures/figure-5.5a.tif",
    width = 6,
    height = 4.5,
    device = "tiff",
    dpi = 600
)

# Housekeeping
moved_tract_nbhd_qual_dt <- NULL
bar_fill <- NULL
bar_colors <- NULL
overall_mean_upward <- NULL
figure_5_5_a <- NULL
rm(
    moved_tract_nbhd_qual_dt,
    bar_fill,
    bar_colors,
    overall_mean_upward,
    figure_5_5_a
)